package com.fish.gaiety.gateway.service.impl;

import com.fish.gaiety.gateway.base.BaseAudit;
import com.fish.gaiety.gateway.entity.UserApi;
import com.fish.gaiety.gateway.entity.dto.Authorities;
import com.fish.gaiety.gateway.entity.dto.User;
import com.fish.gaiety.gateway.repository.AuthoritiesRepository;
import com.fish.gaiety.gateway.repository.UserRepository;
import com.fish.gaiety.gateway.service.AuthoritiesService;
import com.fish.gaiety.gateway.service.UserServiceDeprecated;
import com.fish.gaiety.gateway.util.BaseAuthorities;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Component
@RequiredArgsConstructor
@Deprecated
public class UserServiceDeprecatedImpl implements UserServiceDeprecated, AuthoritiesService {

    private final UserRepository userRepository;

    private final AuthoritiesRepository authoritiesRepository;

    private final PasswordEncoder passwordEncoder;

    @Override
    public UserApi addUserAndGrantBaseAuthority(UserApi userApi,
                                                BaseAuthorities baseAuthorities) {
        User user = userApi.toUser(passwordEncoder);
        User userSaved = userRepository.save(user);
        grantBaseAuthority(userSaved, baseAuthorities);
        return new UserApi(userSaved);
    }

    @Override
    public UserApi addUser(UserApi userApi) {
        return new UserApi(
                userRepository.save(userApi.toUser(passwordEncoder))
        );
    }

    @Override
    public List<User> findAllUsers() {
        return userRepository.findAll();
    }

    @Override
    public User getUser(String id) {
        Long idL = Long.valueOf(id);
        Optional<User> user = userRepository.findById(idL);
        return user.orElse(null);
    }



    @Override
    public void grantBaseAuthority(User user, BaseAuthorities baseAuthorities) {
        Authorities authorities = new Authorities();
        authorities.setBaseAuthorities(baseAuthorities);
        authorities.setUser(user);
        authoritiesRepository.save(authorities);
    }

    @Override
    public Authorities getBaseAuthorityByUserInfo(String userId) {
        User adminUser = getUser(userId);
        return authoritiesRepository.findByUser(adminUser);
    }

    @Override
    @BaseAudit
    public Authorities getBaseAuthorityByUserInfoEnhance(String userId) {
        User adminUser = getUser(userId);
        return authoritiesRepository.findByUser(adminUser);
    }
}
